package com.mrzhou.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mrzhou.system.entity.Role;
import com.mrzhou.core.tool.api.CloudUser;
import com.mrzhou.core.tool.api.R;
import com.mrzhou.core.tool.constants.CloudConstant;
import com.mrzhou.system.entity.RoleMenu;
import com.mrzhou.system.req.EditRoleMenuReq;
import com.mrzhou.system.service.IRoleMenuService;
import com.mrzhou.system.service.IRoleService;
import com.mrzhou.system.vo.MenuVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author qiang.zhou
 */
@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;
    @Autowired
    private IRoleMenuService roleMenuService;

    @PostMapping("submit")
    @ApiOperation("增加或修改")
    public R<String> submit(@Valid @RequestBody Role role) {
        return roleService.submit(role);
    }

    @PostMapping("edit-role-menu")
    @ApiOperation("编辑权限菜单")
    @Transactional
    @CacheEvict(value = CloudConstant.SYS_CACHE, allEntries = true)
    public R<String> editRole(@Valid @RequestBody EditRoleMenuReq req) {
        // 先删除权限对应的全部菜单
        roleMenuService.remove(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getRoleId, req.getRoleId()));
        // 构建权限-菜单数据
        List<RoleMenu> roleMenus = req.getMenus().stream().map(menuId -> {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(req.getRoleId());
            roleMenu.setMenuId(menuId);
            return roleMenu;
        }).collect(Collectors.toList());
        roleMenuService.saveBatch(roleMenus);
        return R.success("操作成功");
    }

    @PostMapping("/user-menu")
    @ApiOperation("获取用户权限对应的菜单信息")
    public R<List<MenuVO>> rolesMenu(CloudUser user) {
        return R.data(roleMenuService.treeRoleMenu(user));
    }


}
